package com.itqf.dao.impl;

import com.itqf.dao.AddressDao;
import com.itqf.pojo.Address;
import com.itqf.utils.C3P0Utils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.SQLException;
import java.util.List;

/**
 * projectName: gpshop
 *
 * @author: 赵伟风
 * time: 2021/7/22 10:34
 * description:
 */
public class AddressDaoImpl implements AddressDao {
    /**
     * 根据用户id查询存在的地址数量
     *
     * @param getuId
     * @return
     */
    @Override
    public long queryCount(int getuId) throws SQLException {

        String sql = "select count(1) from address where u_id = ?";

        QueryRunner queryRunner = new QueryRunner(C3P0Utils.getDataSource());

        Long count = (Long) queryRunner.query(sql, new ScalarHandler(), getuId);

        return count;
    }

    /**
     * 保存地址信息
     *
     * @param address
     * @return
     */
    @Override
    public int insertAddress(Address address) throws SQLException {


        String sql = "insert into address (u_id,a_person,a_phone,a_info,a_state ) value " +
                "(?,?,?,?,?);";

        QueryRunner queryRunner = new QueryRunner(C3P0Utils.getDataSource());

        int rows = queryRunner.update(sql, address.getuId(),address.getaPerson(),address.getaPhone(),
                address.getaInfo(),address.getaState());

        return rows;
    }

    /**
     * 根据用户id查询地址信息
     *
     * @param uid
     * @return
     */
    @Override
    public List<Address> queryAll(int uid) throws SQLException {

        String sql = "select a_id aId,u_id uId,a_person aPerson,a_phone aPhone,a_info aInfo,a_state aState from address " +
                "   where u_id = ?";

        QueryRunner queryRunner = new QueryRunner(C3P0Utils.getDataSource());

        List<Address> addresses = queryRunner.query(sql, new BeanListHandler<>(Address.class), uid);

        return addresses;
    }

    /**
     * 取消全部默认地址
     *
     * @param uId
     * @return
     */
    @Override
    public int updateState(int uId) throws SQLException {

        String sql = "update address set a_state = 0 where u_id = ?;";

        QueryRunner queryRunner = new QueryRunner(C3P0Utils.getDataSource());

        int rows = queryRunner.update(sql, uId);

        return rows;
    }

    /**
     * 设置新的默认地址
     *
     * @param aId
     */
    @Override
    public void setDefualt(String aId) throws SQLException {

        String sql = "update address set a_state = 1 where a_id = ?;";

        QueryRunner queryRunner = new QueryRunner(C3P0Utils.getDataSource());

        int rows = queryRunner.update(sql, aId);
    }
}
